<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Register extends MY_Controller {
    /**
    * Responsable for auto load the model
    * @return void
    */
   public function __construct(){
		parent::__construct();
		$this->load->model('register_m', 'register');
		$this->load->model('users_m', 'users');
		$this->load->model('canhan_m', 'canhan');
		$this->load->model('album_m', 'album');		
		$this->load->helper(array('captcha','util'));
		// if(function_exists('check_captcha')) echo '1111111111';
		// die;
		$this->load->library('form_validation');		
		$this->form_validation->set_message('required', '<strong>%s</strong> cần phải nhập');
		$this->form_validation->set_message('valid_email', '<strong>%s</strong> nhập chưa đúng định dạng');
		$this->form_validation->set_message('alpha', '<strong>%s</strong> chỉ bao gồm các ký tự(A-Z,a-z)');
		$this->form_validation->set_message('min_length', '<strong>%s</strong> tối thiểu phải %s ký tự');
		$this->form_validation->set_message('matches', '<strong>%s</strong> nhập chưa đúng');
		$this->form_validation->set_message('max_length', '<strong>%s</strong> tối đa là %s ký tự');
		$this->form_validation->set_message('greater_than', '<strong>%s</strong> phải lớn hơn %s');
		$this->form_validation->set_message('callback_check_captcha', '<strong>%s</strong> ');
   }
	
	
	function index(){
		if($this->users->is_logged_in())
			redirect('/tai-khoan');
		$data = array();
		$data['content'] = 'register/register';
		$this->load->model('help_m', 'help');
		$data['helps'][] 	= array(
			'title'	=>	'Hướng dẫn đăng ký',
			'help'	=>	$this->help->get_helps('dang_ky'));
		$this->load->view('tpl/template', $data);
	}
	
	function daubep(){
		$data = array();
		$post = $this->input->post();
		//$album = explode(';',$post['album']);
		//echo '<pre>';print_r($post);die;
		if($post){			
			// $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');			
			$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]|callback_check_email');
			$this->form_validation->set_rules('password', 'Mật khẩu', 'required|min_length[6]');
			$this->form_validation->set_rules('repassword', 'Nhập lại mật khẩu', 'required|matches[password]');
			$this->form_validation->set_rules('ho_ten', 'Họ tên', 'trim|required|min_length[4]');
			$this->form_validation->set_rules('ngay_sinh', 'Ngày sinh', 'required|exact_length[10]');
			$this->form_validation->set_rules('gioi_tinh','required');
			$this->form_validation->set_rules('hon_nhan','required');
			$this->form_validation->set_rules('tinh_thanh','required');
			$this->form_validation->set_rules('avatar','trim');			
			$this->form_validation->set_rules('album','trim');			
			$this->form_validation->set_rules('dich_vu[]', 'Sở trường', 'required');
			$this->form_validation->set_rules('di_dong1', 'Di động 1', 'trim|required|min_length[10]|max_length[11]');
			// $this->form_validation->set_rules('di_dong2', 'Di động 2', 'trim');
			// $this->form_validation->set_rules('can_nang', 'Cân nặng', 'required|min_length[2]|max_length[3]');
			// $this->form_validation->set_rules('chieu_cao_m', 'Chiều cao', 'greater_than[0]|required|max_length[1]');			
			// $this->form_validation->set_rules('chieu_cao_cm', 'Chiều cao(cm)', 'greater_than[10]|required|max_length[2]');			
			// $this->form_validation->set_rules('vong_1', 'Vòng 1', 'greater_than[50]|required|max_length[3]');			
			// $this->form_validation->set_rules('vong_2', 'Vòng 2', 'greater_than[50]|required|max_length[3]');			
			// $this->form_validation->set_rules('vong_3', 'Vòng 3', 'greater_than[50]|required|max_length[3]');			
			// $this->form_validation->set_rules('yahoo','trim');
			// $this->form_validation->set_rules('facebook','trim');
			// $this->form_validation->set_rules('hoc_van','trim');
			// $this->form_validation->set_rules('ngoai_ngu','trim');
			// $this->form_validation->set_rules('nang_khieu','trim');
			$this->form_validation->set_rules('noi_ctac_htai','trim');
			$this->form_validation->set_rules('bang_cap_bep','trim');
			$this->form_validation->set_rules('mon_so_truong','trim');
			$this->form_validation->set_rules('cv_mong_muon','trim');
			$this->form_validation->set_rules('kinh_nghiem','trim');
			$this->form_validation->set_rules('tgian_tu','trim');			
			$this->form_validation->set_rules('tgian_den','trim');			
			$this->form_validation->set_rules('captcha', 'Mã bảo mật', 'trim|max_length[6]|callback_check_captcha');			
			if ($this->form_validation->run() == FALSE){
				$data['error'] = validation_errors();
				$this->session->set_flashdata('dich_vu', $this->input->post('dich_vu'));
				// print_r($this->input->post('dich_vu'));die;
			}else{				
				//default values are empty if the customer is new
				//echo '<pre>';print_r($post);die;				
				$this->db->trans_begin();
				//insert users table
				$user = array();
				$user['email']		=	$post['email'];
				$user['password']	=	md5($post['password']);
				$user['loai']		=	1;				
				$user['ngay_tao']	=	date('Y-m-d');
				$user_id = $this->users->create_user($user);
				if($user_id){
					//insert canhan table
					$canhan['user_id']		= $user_id;
					$canhan['ho_ten']			= ucwords(strtolower($post['ho_ten']));
					$canhan['ngay_sinh']		= date('Y-m-d',strtotime(str_replace('/','-',$post['ngay_sinh'])));
					$canhan['gioi_tinh']		= $post['gioi_tinh'];
					$canhan['hon_nhan']		= $post['hon_nhan'];
					$canhan['tinh_thanh_id']= $post['tinh_thanh'];
					$canhan['quan_huyen_id']= $post['quan_huyen'];
					$canhan['di_dong1']		= $post['di_dong1'];
					//$canhan['di_dong2']		= $post['di_dong2'];
					// $canhan['can_nang']		= $post['can_nang'];
					// $canhan['chieu_cao_m']	= $post['chieu_cao_m'];
					// $canhan['chieu_cao_cm']	= $post['chieu_cao_cm'];
					// $canhan['vong1']			= $post['vong_1'];
					// $canhan['vong2']			= $post['vong_2'];
					// $canhan['vong3']			= $post['vong_3'];
					// $canhan['yahoo']			= $post['yahoo'];
					// $canhan['facebook']		= $post['facebook'];
					// $canhan['hoc_van']		= $post['hoc_van'];
					// $canhan['ngoai_ngu']		= $post['ngoai_ngu'];
					// $canhan['nang_khieu']	= $post['nang_khieu'];
					$canhan['noi_ctac_htai']	= $post['noi_ctac_htai'];
					$canhan['bang_cap_bep']		= $post['bang_cap_bep'];
					$canhan['mon_so_truong']	= $post['mon_so_truong'];
					$canhan['cv_mong_muon']		= $post['cv_mong_muon'];
					$canhan['kinh_nghiem']	= $post['kinh_nghiem'];
					$canhan['tgian_tu']		= date('H:i:s', strtotime($post['tgian_tu']));
					$canhan['tgian_den']		= date('H:i:s', strtotime($post['tgian_den']));
					$canhan['avatar']			= $post['avatar'];
					$canhan['ngay_cap_nhat']= date('Y-m-d H:i:s');
					$canhan_id = $this->users->create_canhan($canhan);
					if($canhan_id){
						//dang ky dich vu
						if($post['dich_vu']){
							$obj = array();							
							foreach($post['dich_vu'] as $value){
								$tmp = array();
								$tmp['canhan_id']	= $canhan_id;
								$tmp['dichvu_id']	= $value;
								$obj[] = $tmp;
							}
							$this->canhan->register_services($obj);
						}
						//tao album
						if($album = @json_decode($post['album'])){
							//echo '<pre>';print_r($album);die;
							$obj = array();							
							foreach($album as $value){
								if(!$value)	continue;
								$tmp = array();
								$tmp['canhan_id']	= $canhan_id;
								$tmp['thumb']		= $value;
								$obj[] = $tmp;
							}
							$this->album->create_album_batch($obj);
						}
					}else{
						$this->form_validation->set_message('create_user', "Tạo tài khoản không thành công.");
					}
				}else{
					$this->form_validation->set_message('create_user', "Tạo tài khoản không thành công.");
				}
				//
				if ($this->db->trans_status() === FALSE){
					$this->db->trans_rollback();
				}else{
					$this->db->trans_commit();
					$this->session->set_flashdata('success', array('email'=>$post['email'],'ho_ten'=>ucwords($post['ho_ten'])));
					redirect(site_url('dang-ky/thanh-cong'));					
				}				
			}
		}		
		$data['tinh_thanh'] 	= $this->register->get_tinh_thanh();
		$data['quan_huyen']	= $this->register->get_quan_huyen(set_value('tinh_thanh')?set_value('tinh_thanh'):1, true);
		//echo '<pre>';print_r($data['tinh_thanh']);die;
		$this->load->model('dichvu_m', 'dichvu');		
		foreach($this->dichvu->get_dichvu() as $obj)
			$data['dichvu'][$obj->id] = $obj->ten;
		// echo $this->db->last_query();die;
		/* Generate the captcha */
		//captcha
		$cap_word = random_string('alpha',6);
		$vals = array(
			'word'	=>	strtoupper($cap_word),
			'font_path'	=>	'assets/fonts/VERDANAB.TTF',
			'img_path' => 'uploads/captcha/',
			'img_url' => base_url().'uploads/captcha/',
			'img_width'	 => '120',
			'img_height' => 30,
			'expiration' => 7200
		);
		$captcha = create_captcha($vals);
		/* Store the captcha value (or 'word') in a session to retrieve later */
		$this->session->set_userdata('captcha', $captcha['word']);
		$data['captcha'] = $captcha['image'];		
		$data['content'] = 'register/daubep';
		//$data['quangcao'] = 'tpl/quangcao';
		$this->load->view('tpl/template', $data);
	}
	
	function nhatuyendung(){
		$data = array();
		$post = $this->input->post();
		// echo '<pre>';print_r($post);die;
		if($post){
			// $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>', '</div>');
			$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]|callback_check_email');
			$this->form_validation->set_rules('password', 'Mật khẩu', 'required|min_length[6]');
			$this->form_validation->set_rules('repassword', 'Nhập lại mật khẩu', 'required|matches[password]');
			$this->form_validation->set_rules('ten', 'Tên', 'trim|required|min_length[6]');
			$this->form_validation->set_rules('nguoi_lien_he', 'Người liên hệ', 'trim');
			$this->form_validation->set_rules('dia_chi', 'Địa chỉ', 'trim');
			$this->form_validation->set_rules('avatar','trim');			
			$this->form_validation->set_rules('dien_thoai', 'Di động 1', 'trim');
			$this->form_validation->set_rules('di_dong', 'Di động 2', 'trim');
			$this->form_validation->set_rules('captcha', 'Mã bảo mật', 'trim|max_length[6]|callback_check_captcha');			
			if ($this->form_validation->run() == FALSE)
				$data['error'] = validation_errors();
			else{
				$this->db->trans_begin();
				//insert users table
				$user = array();
				$user['email']		=	$post['email'];
				$user['password']	=	md5($post['password']);
				$user['loai']		=	2;
				$user['ngay_tao']	=	date('Y-m-d');
				$user_id = $this->users->create_user($user);
				if($user_id){
					//insert nhatuyendung table
					$obj['user_id']		= $user_id;
					$obj['ten']				= $post['ten'];
					$obj['gioi_thieu']	= $post['gioi_thieu'];
					$obj['nguoi_lien_he']= $post['nguoi_lien_he'];
					$obj['dia_chi']		= $post['dia_chi'];
					$obj['dien_thoai']	= $post['dien_thoai'];
					$obj['di_dong']		= $post['di_dong'];
					$obj['avatar']			= $post['avatar'];
					$obj['ngay_cap_nhat']= date('Y-m-d H:i:s');
					$obj_id = $this->users->create_nhatuyendung($obj);
				}else{
					$this->form_validation->set_message('create_user', "Tạo tài khoản không thành công.");
				}
				//
				if ($this->db->trans_status() === FALSE){
					$this->db->trans_rollback();
				}else{
					$this->db->trans_commit();
					$this->session->set_flashdata('success', array('email'=>$post['email'],'ho_ten'=>ucwords($post['ten'])));
					redirect(site_url('dang-ky/thanh-cong'));					
				}				
			}
		}
		//captcha
		$cap_word = random_string('alpha',6);
		$vals = array(
			'word'	=>	strtoupper($cap_word),
			'font_path'	=>	'assets/fonts/VERDANAB.TTF',
			'img_path' => 'uploads/captcha/',
			'img_url' => base_url().'uploads/captcha/',
			'img_width'	 => '120',
			'img_height' => 30,
			'expiration' => 7200
		);
		/* Generate the captcha */
		$captcha = create_captcha($vals);
		$this->session->set_userdata('captcha', $captcha['word']);
		$data['captcha'] = $captcha['image'];
		$data['content'] = 'register/nhatuyendung';
		// $data['quangcao'] = 'tpl/quangcao';
		$this->load->view('tpl/template', $data);
	}
	
	function raovat(){
		$data = array();
		$data['content'] = 'register/raovat';
		$data['quangcao'] = 'tpl/quangcao';
		$this->load->view('tpl/template', $data);
	}
	
	function get_quan_huyen(){
		$tinh_id = $this->input->post('tinh_id');
		$html = '<select name="quan_huyen" class="form-control">';
		$html .= '<option value="0">Tất cả</option>';
		if($tinh_id){
			foreach($this->register->get_quan_huyen($tinh_id) as $obj)
				$html .= '<option value="'.$obj->id.'">'.$obj->ten.'</option>';
		}
		$html .= '</select>';			
		echo $html;
		die;
	}
	
	function thanhcong(){
		$data['content'] = 'register/thanhcong';
		//$data['quangcao'] = 'tpl/quangcao';
		$this->session->set_userdata('message', 'Bạn đã đăng ký thành công, vui lòng đăng nhập để cập nhật thông tin hồ sơ hoàn chỉnh');
		$this->load->view('tpl/template', $data);
	}
	
	function login(){
		if($this->users->is_logged_in())
			redirect('/tai-khoan');
		$post = $this->input->post();
		if($post){
			$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]');
			$this->form_validation->set_rules('password', 'Mật khẩu', 'required|min_length[6]');
			$this->form_validation->set_rules('return', 'return', 'trim');
			$this->form_validation->run();
			$email 		= isset($post['email']) ? $post['email'] : '';
			$password 	= isset($post['password']) ? $post['password'] : '';
			$return	= isset($post['return']) ? $post['return'] : '/tai-khoan';
			$remember	= isset($post['remember']) ? true : false;
			//echo '<pre>';var_dump($this->users->login($email,$password, $remember));die;
			if($this->users->login($email,$password, $remember))
				if($return)
					redirect($return);
				else
					redirect('tai-khoan');
			else{
				$this->session->set_userdata('danger', '<strong>Email</strong> hoặc <strong>Mật khẩu</strong> chưa đúng, vui lòng thử lại.');
			}
		}
		$data['content'] = 'register/dangnhap';
		$this->load->model('help_m', 'help');
		$data['helps'][] 	= array(
			'title'	=>	'Hướng dẫn đăng ký',
			'help'	=>	$this->help->get_helps('dang_ky'));
		$this->load->view('tpl/template', $data);
	}
	
	function logout(){
		$this->users->logout();
		redirect(site_url());
	}
	
	function resetpassword(){
		$data = array();
		$post = $this->input->post();
		// echo '<pre>';print_r($post);die;
		if($post){
			$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]');
			$this->form_validation->set_rules('captcha', 'Mã bảo mật', 'trim|max_length[6]|callback_check_captcha');			
			if ($this->form_validation->run() == FALSE)
				$this->session->set_flashdata('danger', validation_errors());
			else{
				//insert users table
				$email		=	$post['email'];
				$password	= random_string('alnum',6);		
				if($result = $this->users->update_user($email, $password)){
					if($this->config->item('email_register')){						
						$this->load->library('email');
						$res	=	$this->email->send_mail(array(
							'slug'		=>	'reset-mat-khau',
							'to'			=>	$email,
							'email'		=>	$email,
							'ho_ten'		=>	$result->ho_ten,
							'password'	=>	$password
						));
						if($res)
							$this->session->set_flashdata('message', "Hãy kiểm tra email của bạn để có thông tin đăng nhập vào hệ thống.");
						else
							$this->session->set_flashdata('danger', "Có lỗi xảy ra. Vui lòng liên hệ với ban quản trị.");
					}
				}else{
					$this->session->set_flashdata('danger', "Không tồn tại email trong hệ thống.");
				}
				redirect('dang-ky/quen-mat-khau');
			}
		}
		//captcha
		$cap_word = random_string('alnum',6);
		$vals = array(
			'word'	=>	strtoupper($cap_word),
			'font_path'	=>	'assets/fonts/VERDANAB.TTF',
			'img_path' => 'uploads/captcha/',
			'img_url' => base_url().'uploads/captcha/',
			'img_width'	 => '120',
			'img_height' => 30,
			'expiration' => 7200
		);
		/* Generate the captcha */
		$captcha = create_captcha($vals);
		$this->session->set_userdata('captcha', $captcha['word']);
		$data['captcha'] = $captcha['image'];
		$data['content'] = 'register/resetpassword';
		$this->load->model('help_m', 'help');
		$data['helps'][] 	= array(
			'title'	=>	'Hướng dẫn đăng ký',
			'help'	=>	$this->help->get_helps('dang_ky'));
		$this->load->view('tpl/template', $data);
	}	
	
	function check_email($str){
		$email = $this->register->check_email($str);
      if ($email){
			$this->form_validation->set_message('check_email', '<strong>Email</strong> đã được đăng ký');
			return FALSE;
		}else{
			return TRUE;
		}
	}
	
	function send_email(){
		$email	=	$this->input->post('email');
		$ho_ten	=	$this->input->post('hoTen');		
		if(!$email || !$ho_ten)
			die('fail');
		if(!$this->config->item('email_register'))
			die('fail');
		$this->load->library('email');
		$res	=	$this->email->send_mail(array(
			'slug'	=>	'xac-nhan-dang-ky',
			'to'		=>	$email,
			'ho_ten'	=>	$ho_ten
		));
		if($res)
			die('success');
		else
			die('fail');
	}
}